// app/service/contract.js
const diff = require('diff');

class ContractService {
  /**
   * 对比两个合同模板版本差异
   * @param {number} templateId1 - 模板ID1
   * @param {number} templateId2 - 模板ID2
   * @returns {Object} 差异结果
   */
  async compareTemplateVersions(templateId1, templateId2) {
    const [template1, template2] = await Promise.all([
      this.ctx.model.ContractTemplate.findByPk(templateId1),
      this.ctx.model.ContractTemplate.findByPk(templateId2)
    ]);

    if (!template1 || !template2) {
      this.ctx.throw(404, '合同模板不存在');
    }

    // 先比较版本哈希，如果相同则无需详细对比
    if (template1.version_hash === template2.version_hash) {
      return { identical: true, changes: [] };
    }

    // 生成详细差异报告
    const differences = diff.diffLines(template1.content, template2.content);
    const changes = differences.map(change => ({
      type: change.added ? 'added' : change.removed ? 'removed' : 'unchanged',
      content: change.value,
      lineNumbers: this._getLineNumbers(change.value)
    }));

    // 记录版本对比审计日志
    await this.ctx.model.ContractTemplateAudit.create({
      operator_id: this.ctx.user.id,
      action: 'VERSION_COMPARE',
      template_id1: templateId1,
      template_id2: templateId2,
      ip_address: this.ctx.ip
    });

    return { identical: false, changes };
  }

  /**
   * 获取内容的行号范围
   * @private
   */
  _getLineNumbers(content) {
    const lines = content.split('\n');
    return { start: 1, end: lines.length };
  }

  async signElectronicContract(params) {
    const pdfBuffer = await this._generateContractPDF(params);
    const encryptedPDF = this.ctx.service.zcyCrypto.encryptSM4(pdfBuffer);

    const txHash = await this.ctx.service.blockchain.record({
      action: 'CONTRACT_SIGN',
      hash: this.ctx.helper.fileHash(encryptedPDF)
    });

    await this.ctx.model.Contract.create({
      ...params,
      pdf: encryptedPDF,
      tx_hash: txHash,
      status: 'effective'
    });
  }
}